import os
import sys
import time

import psutil
from fastapi import FastAPI,Request,status
import uvicorn

from fastapi.staticfiles import StaticFiles
from starlette.responses import JSONResponse
from tortoise.contrib.fastapi import register_tortoise

from apps.admin.AdminUser import user
from apps.api.User import user as apiUser
from apps.api.Login import loginScene
from apps.api.Upload import upload
from apps.api.Student import student_api
from common.ResponseModel import ResponseModel
from config import TORTOISE_ORM
from fastapi.middleware.cors import CORSMiddleware

from middleware.LoggingMiddleware import LoggingMiddleware
from loguru import logger
from prometheus_fastapi_instrumentator import Instrumentator
from pydantic import BaseModel


class HealthCheckResponse(BaseModel):
    status: str
    system_info: dict
    dependencies: dict

# 添加日志
# 日志配置

# ===== Loguru日志配置 =====
def configure_logging():
    # 移除默认handler
    logger.remove()

    # 配置控制台输出
    logger.add(
        sink=sys.stdout,
        format="<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>",
        level="DEBUG" if os.getenv("DEBUG") else "INFO",
        enqueue=True  # 异步安全
    )

    # 配置文件输出
    logger.add(
        sink="logs/app_{time:YYYY-MM-DD}.log",
        rotation="00:00",  # 每天轮转
        retention="30 days",
        compression="zip",
        serialize=True  # 结构化日志
    )

def get_system_status():
    """获取系统健康状态"""
    mem = psutil.virtual_memory()
    return {
        "cpu_percent": psutil.cpu_percent(),
        "memory_used": f"{mem.used / (1024**3):.1f}GB",
        "memory_total": f"{mem.total / (1024**3):.1f}GB",
        "disk_usage": psutil.disk_usage('/').percent
    }

def check_database():
    """检查数据库连接"""
    # 这里添加实际的数据库连接测试代码
    return {"database": "ok"}

app = FastAPI()

# 配置日志
configure_logging()

# 添加监控
instrumentator = Instrumentator()
instrumentator.instrument(app).expose(app)


# 全局异常处理
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    logger.error(
        "Unhandled exception occurred",
        path=request.url.path,
        method=request.method,
        error=str(exc),
        exc_info=True
    )
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content= ResponseModel.error(code=status.HTTP_500_INTERNAL_SERVER_ERROR,message="internal server")
    )
# 配置允许列表
origins = [
    "*"
]


# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE","OPTION"],
    allow_headers=["*"],
)



#添加日志中间件
app.add_middleware(LoggingMiddleware)

# 设置静态文件访问
app.mount("/static", StaticFiles(directory="static"))

app.include_router(user, prefix="/admin", tags=["后台"])
app.include_router(loginScene, prefix="/api/login", tags=["小程序"])
app.include_router(apiUser, prefix="/api/user", tags=["小程序"])
app.include_router(upload, prefix="/api/upload", tags=["小程序"])
app.include_router(student_api, prefix="/api/student", tags=["小程序"])

# health_check
@app.get("/health", response_model=HealthCheckResponse, tags=["monitoring"],summary="系统监控检查")
async def health_check():
    system_status = get_system_status()
    dependencies = {
       **check_database(),
        # 添加其他依赖检查
    }

    status_code = "healthy" if all(
        v == "ok" for v in dependencies.values()
    ) else "degraded"

    logger.info("Health check", status_code=status_code,system_status = system_status,dependencies = dependencies)

    return {
        "status": status_code,
        "system_info": system_status,
        "dependencies": dependencies
    }


# 注册数据库
register_tortoise(
    app=app,
    config=TORTOISE_ORM,
    # generate_schemas=True,
    add_exception_handlers=True,    #调试
)


if __name__ == '__main__':
    uvicorn.run("quick-start:app", port=8080, reload=True)
